<template>
  <div>
    <el-form size="large" ref="bookBorrowRef" :model="bookBorrowForm" :rules="rules">
      <el-form-item label="借阅者编号">
        <el-autocomplete
            v-model="bookBorrowForm.readerId"
            :fetch-suggestions="querySearchAsync"
            placeholder="请输入读者学号"
            @select="handleSelect"
            :trigger-on-focus="false"
        />
      </el-form-item>
      <el-form-item label="已选图书">
        <book-card :book="item" v-for="item in bookList"></book-card>
        <div class="plus-box" @click="dialogVisible = true">
          <el-icon class="plus-icon">
            <Plus/>
          </el-icon>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" style="width: 100%" @click="submitBookBrook(bookBorrowRef)">借阅</el-button>
      </el-form-item>
    </el-form>
    <el-dialog
        v-model="dialogVisible"
        title="选择借阅图书"
        width="900"
    >
      <el-form :model="bookQueryForm" inline ref="queryRef">
        <el-form-item label="图书ID" prop="bookId">
          <el-input v-model="bookQueryForm.bookId"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getBookPage" icon="Search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="bookQueryForm.bookId=''" icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="bookPage.list" v-loading="loading" ref="bookTableRef">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="bookId" label="图书ID"></el-table-column>
        <el-table-column label="封面">
          <template #default="scoped">
            <el-icon size="40">
              <el-image :src="scoped.row.cover"/>
            </el-icon>
          </template>
        </el-table-column>
        <el-table-column prop="isbn" label="ISBN"></el-table-column>
        <el-table-column prop="title" label="图书名称"></el-table-column>
        <el-table-column prop="subtitle" label="副标题"></el-table-column>
        <el-table-column prop="author" label="作者"></el-table-column>
        <el-table-column prop="publisher" label="出版社"></el-table-column>
        <el-table-column prop="publishDate" label="出版日期"></el-table-column>
        <el-table-column prop="price" label="定价"></el-table-column>
        <el-table-column prop="stock" label="库存"></el-table-column>
        <el-table-column prop="edition" label="版次"></el-table-column>
        <el-table-column prop="location" label="图书位置"></el-table-column>
        <el-table-column prop="status" label="状态"></el-table-column>
        <el-table-column prop="categoryId" label="分类ID"></el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmSelectedBooks">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {onMounted, reactive, ref, watch} from "vue";
import {useRoute} from "vue-router";
import {reqBorrowBook} from "@/api/borrow-record/index.js";
import {reqGetReaderPage} from "@/api/reader/index.js";
import BookCard from "@/components/book/BookCard.vue";
import {reqGetBookPageList} from "@/api/book/index.js";

const route = useRoute()
let bookBorrowForm = reactive({
  readerId: route.query.readerId ? route.query.readerId : '',
  bookIdList: []
})
let bookList = ref([])
let loading = ref(true)
let errorBookList = ref(null)
let bookBorrowRef = ref(null)
let bookTableRef = ref()
let readerQueryForm = reactive({
  pageNum: 1,
  pageSize: 10,
  keyword: '',
  typeId: '',
  readerNo: ''
})
let bookQueryForm = reactive({
  pageNum: 1,
  pageSize: 10,
  bookId: ''
})
let dialogVisible = ref(false)
let bookPage = reactive({
  total: 0,
  pageNum: 1,
  list: []
})

let getBookPage = () => {
  reqGetBookPageList(bookQueryForm).then((res) => {
    Object.assign(bookPage, res.data)
    loading.value = false
  })
}
let confirmSelectedBooks = () => {
  if (bookTableRef.value) {
    const selectedBooks = bookTableRef.value.getSelectionRows()
    if (selectedBooks && selectedBooks.length > 0) {
      const newBooks = selectedBooks.filter(book =>
          !bookList.value.some(item => item.bookId === book.bookId)
      )
      if (newBooks.length > 0) {
        bookList.value = [...bookList.value, ...newBooks]
        bookBorrowForm.bookIdList = bookList.value.map(book => book.bookId)
      }
    }
    dialogVisible.value = false
  }
}
let submitBookBrook = async (formEl) => {
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      let res = await reqBorrowBook(bookBorrowForm)
      errorBookList.value = res.data
    } else {
      console.log('error submit!', fields)
    }
  })
}
const handleSelect = (item) => {
  bookBorrowForm.readerId = item.value
}
const querySearchAsync = async (queryString, callback) => {
  readerQueryForm.readerNo = queryString
  try {
    let res = await reqGetReaderPage(readerQueryForm)
    const suggestions = res.data.list.map(item => ({
      value: item.readerId,
      label: item.name
    }))
    callback(suggestions)
  } catch (error) {
    console.error('搜索读者时出错:', error)
    callback([])
  }
}
let rules = {
  readerId: [
    {required: true, message: '请输入借阅者编号', trigger: 'blur'},
  ],
  bookIdList: [
    {required: true, message: '请输入图书编号', trigger: 'blur'},
  ]
}
watch(() => dialogVisible.value, () => {
  if (dialogVisible) {
    console.log("触发")
    getBookPage()
  }
})
</script>

<style scoped>
.plus-box {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.plus-box:hover {
  border-color: var(--el-color-primary);
}

.el-icon.plus-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
